<template>
  <div>
    <!-- 角色列表 -->
    <!-- 表头  面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 视图-->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisiable = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <!-- 插槽 组件 -->
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', al === 0 ? 'bdtop' : '', 'venter']"
              v-for="(item1, al) in scope.row.children"
              :key="item1.id"
            > <!-- children 所有一级权限 -->
           
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>  <!-- 图标 -->
              </el-col>
              <!-- 渲染二级权限和渲染二级权限 -->
              <el-col :span="19">
                <!-- 通过for循环,嵌套二级权限 -->
                <el-row
                  :class="[a2 !== 0 ? '' : 'bdtop', 'venter']"
                  v-for="(item2, a2) in item1.children"
                  :key="item2.id"
                  >
                  <!-- //警告提示 warning-->
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      type="warning"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 通过for循环,嵌套三级级权限 closable删除标签  scope.row角色id-->
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      type="success"
                      >
                      {{ item3.authName }}
                      </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{scope.row}}
            </pre>        插槽组件的数据-->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" prop="roleDesc" width="350px">
          <!-- 插槽 -->
          <template slot-scope="scope">
            <!-- 编辑 组件  按钮大小化 颜色，图标-->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeUserById(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配权限 -->
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSet(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisiable"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="80px"
        :rules="addFormRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色的对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisiable"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="80px"
        :rules="editFormRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="权限分配"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRightsDialogClosed"
    >
      <!-- 树行空间 rightsList数据绑定  show-checkbox复选框 node-key="id"节点  default-expand-all默认打胎节点-->
      <!--:default-checked-keys="defkeys"默认树形节点  -->
      <el-tree
        node-key="id"
        show-checkbox
        :data="rightsList"
        :props="treeProps"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //用于保存请求到的数据 所有角色来表示数据
      rolesList: [], 
      //控制添加对话框显示和隐藏
      addDialogVisiable: false,
      //  添加用户的表单数据
      // 添加用户
      addForm: {
        roleName: "", // 角色名称
        roleDesc: "", //角色描述
      },
      // 添加用户规则
      // 角色名称
      addFormRules: {
        roleName: [
          { required: true, message: "请输入用户名!", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 12 个字符", trigger: "blur" },
        ],
        //角色描述
        roleDesc: [
          { required: true, message: "请输入密码!", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
      },

      //控制修改对话框显示和隐藏
      editDialogVisiable: false,
      //修改用户信息对象
      editForm: {
        roleName: "", // 角色名称
        roleDesc: "", //角色描述
        roleId: "", //角色id
      },
      // 修改角色规则
      editFormRules: {
        roleName: [
          { required: true, message: "请输入用户名!", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 12 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入密码!", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
      // 控制分配权限对话框显示和隐藏
      setRightsDialogVisible: false,
      //得到的分配权限的数据  所有权限数据
      rightsList: [],
      //树形控件的属性绑定对象
      treeProps: {
        label: "authName", //一级数据管理
        children: "children",//二,三级数据管理
      },
      //默认选中的权限 
      defkeys: [],
      //以选中的角色ID值 当前即将分配权限的id
      roleId: "",
    }
  },
  created() {
    //生命周期函数
    // 页面启动，调用函数getRightsList
    this.getRolesList()
  },
  methods: {
    //获得所有角色数据列表
    async getRolesList() {
      // axios请求后台数据
      const { data: res } = await this.$http.get("roles")
      // 失败提示
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限失败！")
      }
      this.rolesList = res.data //获取数据成功
      console.log(this.rolesList)
    },
    //监听用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //点击按钮，添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return
        const { data: res } = await this.$http.post("roles", this.addForm)
        if (res.meta.status !== 200) {
          this.$message.error("添加用户失败！")
        }
        this.$message.success("添加用户成功！")
        // 点击按钮，隐藏对话框
        this.addDialogVisiable = false
        // 重新获取用户列表数据
        this.getRolesList()
      })
    },
    //根据id删除用户信息
    async removeUserById(id) {
      ///获取数据成功
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => {
        return err
      })
      //如果用户确认删除，则返回值为字符串 confirm
      //如果用户取消，返回值为字符串 cancal
      if (confirmResult !== "confirm") {
        return this.$message.info("用户取消删除")
      }
      const { data: res } = await this.$http.delete("roles/" + id)
      if (res.meta.status !== 200) {
        return this.$message.error("用户删除失败！")
      }
      this.$message.success("用户删除成功！")
      this.getRolesList() // 重新获取用户列表数据
    },

    //点击按钮， 修改用户
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("roles/" + id)
      //请求失败处理结果
      if (res.meta.status !== 200) {
        this.$message.error("查询用户失败！")
      }
      this.editForm = res.data //刷新获得的数据//
      // 点击按钮，隐藏对话框
      // 重新获取用户列表数据

      this.getRolesList()
      this.editDialogVisiable = true //关闭对话框
    },
    //监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },

    //修改信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        //校验 表单预验证
        if (!valid) return
        //发起数据请求
        const { data: res } = await this.$http.put(
          "roles/" + this.editForm.roleId,
          { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc }
        )

        if (res.meta.status !== 200) {
          return this.$message.error("更新用户信息失败！")
        }
        //关闭对话框
        this.editDialogVisiable = false
        //提示修改成功
        this.$message.success("用户信息修改成功！")
        //刷新数据
        this.getRolesList()
      })
    },

    //根据ID删除对应权限   删除权限  role权限id, right角色id
    async removeRightById(role, right) {
      //弹框提示用户是否要删除 
      const confirmResult = await this.$confirm(
        "此操作将删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",  //警告提示
        }
      ).catch((err) => err)
      // 点击取消，弹出信息
      if (confirmResult !== "confirm") {
        return this.$message.info("取消了更改权限")
      }
      // console.log('确认了删除');
      // 删除请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${right}` //路径请求删除id
      )
      if (res.meta.status !== 200) {warning
        return this.$message.error("删除失败！")
      }
      this.$message.success("成功更改权限！") //弹框提示
      //data为最新权限
      //把服务器最先的权限返回给children
      role.children = res.data
    },
    //分配权限 展示分配权限的对话框
    async showSet(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get("rights/tree") //树形结构
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限失败")
      }//把获取的权限数据保存到 data 中
      this.rightsList = res.data
      console.log(this.rightsList)
      //调用递归函数获取三级节点的Id
      this.getLeafKeys(role, this.defkeys) //role为scope.row形参
      this.setRightsDialogVisible = true
    },

    // 通过递归的形式，获取角色下所有三级权限的id，并保存到defkeys
    getLeafKeys(node, arr) {
      //如果nod节点不包括children属性，则为三级节点
      if (!node.children) {
        //this.defkeys为arr实参
        return arr.push(node.id)
      }
      //循环node里面的所有数组
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    //监听分配权限对话框的关闭事件
    setRightsDialogClosed() {
      this.defkeys = []
    },
    //点击分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),//所有已选中节点的函数
        ...this.$refs.treeRef.getHalfCheckedKeys(),//所有没选中节点的函数
      ]
      console.log(keys)
      const idStr = keys.join(",")
      console.log(idStr)
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr,
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败")//弹框失败
      }
      this.$message.success("分配权限成功")//弹框成功
      this.getRolesList()
      this.setRightsDialogVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.venter {
  display: flex;
  align-items: center;
}
</style>